<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Employee extends Model
{
    use HasFactory;

    /**
     * 表名
     */
    protected $table = 'employees';

    /**
     * 可填充的字段
     */
    protected $fillable = [
        'user_id',
        'employee_no',
        'name',
        'gender',
        'birth_date',
        'id_card_number',
        'phone',
        'email',
        'address',
        'emergency_contact',
        'emergency_phone',
        'hire_date',
        'contract_start_date',
        'contract_end_date',
        'position',
        'department',
        'salary_grade',
        'basic_salary',
        'status',
        'work_location',
        'manager_id',
        'probation_end_date',
        'regular_date',
        'termination_date',
        'termination_reason',
        'notes',
    ];

    /**
     * 类型转换
     */
    protected $casts = [
        'birth_date' => 'date',
        'hire_date' => 'date',
        'contract_start_date' => 'date',
        'contract_end_date' => 'date',
        'probation_end_date' => 'date',
        'regular_date' => 'date',
        'termination_date' => 'date',
        'basic_salary' => 'decimal:2',
    ];

    /**
     * 获取关联的用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 获取所属部门
     * 注意：实际数据库中可能没有department_id字段，需要根据实际情况调整
     */
    public function departmentInfo(): BelongsTo
    {
        return $this->belongsTo(Department::class, 'department_id');
    }

    /**
     * 获取所属岗位
     * 注意：实际数据库中可能没有position_id字段，需要根据实际情况调整
     */
    public function positionInfo(): BelongsTo
    {
        return $this->belongsTo(Position::class, 'position_id');
    }

    /**
     * 获取上级领导
     */
    public function manager(): BelongsTo
    {
        return $this->belongsTo(Employee::class, 'manager_id');
    }

    /**
     * 获取下属员工
     */
    public function subordinates(): HasMany
    {
        return $this->hasMany(Employee::class, 'manager_id');
    }

    /**
     * 获取教育经历
     */
    public function educationExperiences(): HasMany
    {
        return $this->hasMany(EducationExperience::class);
    }

    /**
     * 获取内部工作经历
     */
    public function internalExperiences(): HasMany
    {
        return $this->hasMany(InternalExperience::class);
    }

    /**
     * 获取外部工作经历
     */
    public function externalExperiences(): HasMany
    {
        return $this->hasMany(ExternalExperience::class);
    }

    /**
     * 获取家庭关系
     */
    public function familyRelations(): HasMany
    {
        return $this->hasMany(FamilyRelation::class);
    }

    /**
     * 获取能力维度评估
     */
    public function abilityAssessments(): HasMany
    {
        return $this->hasMany(AbilityAssessment::class);
    }

    /**
     * 获取员工部门岗位关系
     */
    public function departmentPositions(): HasMany
    {
        return $this->hasMany(EmployeeDepartmentPosition::class);
    }

    /**
     * 获取合同信息
     */
    public function contracts(): HasMany
    {
        return $this->hasMany(Contract::class);
    }

    /**
     * 获取考勤记录
     */
    public function attendanceRecords(): HasMany
    {
        return $this->hasMany(AttendanceRecord::class);
    }

    /**
     * 获取薪资记录
     */
    public function salaryRecords(): HasMany
    {
        return $this->hasMany(SalaryRecord::class);
    }

    /**
     * 获取保险记录
     */
    public function insuranceRecords(): HasMany
    {
        return $this->hasMany(InsuranceRecord::class);
    }

    /**
     * 获取工伤记录
     */
    public function workInjuryRecords(): HasMany
    {
        return $this->hasMany(WorkInjuryRecord::class);
    }

    /**
     * 获取绩效评估
     */
    public function performanceAssessments(): HasMany
    {
        return $this->hasMany(PerformanceAssessment::class);
    }

    /**
     * 获取试岗记录
     */
    public function probationRecords(): HasMany
    {
        return $this->hasMany(ProbationRecord::class);
    }

    /**
     * 获取员工状态标签
     */
    protected function statusLabel(): Attribute
    {
        return Attribute::make(
            get: function () {
                return match ($this->status) {
                    'active' => '在职',
                    'probation' => '试用期',
                    'regular' => '正式员工',
                    'suspended' => '停职',
                    'terminated' => '离职',
                    'retired' => '退休',
                    default => '未知',
                };
            }
        );
    }

    /**
     * 获取性别标签
     */
    protected function genderLabel(): Attribute
    {
        return Attribute::make(
            get: function () {
                return match ($this->gender) {
                    'male' => '男',
                    'female' => '女',
                    default => '未知',
                };
            }
        );
    }

    /**
     * 获取年龄
     */
    protected function age(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!$this->birth_date) {
                    return null;
                }
                return now()->diffInYears($this->birth_date);
            }
        );
    }

    /**
     * 获取工龄
     */
    protected function workYears(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!$this->hire_date) {
                    return null;
                }
                return now()->diffInYears($this->hire_date);
            }
        );
    }

    /**
     * 获取合同状态
     */
    protected function contractStatus(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!$this->contract_end_date) {
                    return '无固定期限';
                }

                if (now()->isAfter($this->contract_end_date)) {
                    return '已到期';
                }

                $daysUntilExpiry = now()->diffInDays($this->contract_end_date);
                if ($daysUntilExpiry <= 30) {
                    return '即将到期';
                }

                return '正常';
            }
        );
    }

    /**
     * 作用域：在职员工
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 作用域：按部门筛选
     */
    public function scopeByDepartment($query, int $departmentId)
    {
        return $query->where('department_id', $departmentId);
    }

    /**
     * 作用域：按岗位筛选
     */
    public function scopeByPosition($query, int $positionId)
    {
        return $query->where('position_id', $positionId);
    }

    /**
     * 作用域：按状态筛选
     */
    public function scopeByStatus($query, string $status)
    {
        return $query->where('status', $status);
    }

    /**
     * 作用域：试用期员工
     */
    public function scopeInProbation($query)
    {
        return $query->where('status', 'probation');
    }

    /**
     * 作用域：即将到期的合同
     */
    public function scopeContractExpiring($query, int $days = 30)
    {
        return $query->where('contract_end_date', '<=', now()->addDays($days))
                    ->where('contract_end_date', '>', now());
    }
}